package controller.menubar.commands;
import java.awt.Toolkit;
import java.io.File;
import javax.swing.SwingWorker;

import view.MainFrame;


class DeleteFile extends SwingWorker<Void, Void> {
		
		private File from;		
		private MainFrame frame;		
		private static long size;
		private long totalBytes = 0L;
        
		
		DeleteFile(File from, MainFrame frame) {				
			this.from = from;						
			this.frame = frame;
			size = 0;			
		}		
		
		@Override
		public Void doInBackground() {		
			//System.out.println(from.getAbsolutePath());
			retrieveTotalBytes(from);
			deleteFolder(from);	
			size = 0;
			frame.getMainPanel().getPrimary().getDiskContent().CreateNewView(null);
			frame.getMainPanel().getSecondary().getDiskContent().CreateNewView(null);
			setProgress(100);
			return null;			
		}	
		
		private void retrieveTotalBytes(File sourceFile)
        {
        	if(sourceFile.isDirectory()) {
        		File[] files = sourceFile.listFiles();
        		for(File file : files)
                {                    
        			retrieveTotalBytes(file);
                }        		
        	}     	
            else totalBytes += sourceFile.length();
            
        }
		
		public void deleteFolder(File folder) {
		    File[] files = folder.listFiles();
		    if(files!=null) { 
		        for(File f: files) {
		            if(f.isDirectory()) {
		                deleteFolder(f);
		            } else {		                              
		                size += f.getTotalSpace();
		                setProgress((int) (size / totalBytes));
		                f.delete();		  
		            }
		        }
		    }
		    
		    folder.delete();
		}
		
		@Override
		public void done() {
			Toolkit.getDefaultToolkit().beep();	
			frame.getMainPanel().getPrimary().getDiskContent().CreateNewView(null);
			frame.getMainPanel().getSecondary().getDiskContent().CreateNewView(null);
		}
}
	

